package org.halo.trade.data.sina;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.FutureRequestExecutionService;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpRequestFutureTask;
import org.halo.trade.data.config.Config;
import org.halo.trade.data.http.BytesResponseHandler;
import org.halo.trade.data.http.HttpResult;
import org.halo.trade.data.http.ResultResponseHandler;
import org.halo.trade.data.http.StringResponseHandler;
import org.halo.trade.data.tool.CodeRecognizer;
import org.halo.trade.data.tool.UUAPI;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/*
 * 新浪的数据采集器
 * */
public class DefaultSinaDataUtilis implements IDatatUtils
{
	private String cookiesFile = Utils.getTempPath() + "/cookies_sina.obj";
	//cookie存储
	private BasicCookieStore cookieStore = new BasicCookieStore();
	//请求client
	private HttpClient httpClient = null;
	//执行器
	private ExecutorService execService = null;
	private FutureRequestExecutionService requestExecService = null;
	private SinaParameter preLoginPara = new SinaParameter();
	private String clientIp = "";
	private boolean isLogined = false; 
	//验证码识别
	private CodeRecognizer regocgnizer = CodeRecognizer.getInstance();
	private int lastImgCodeId = 0;
	private String lastCode = null;
	private String username = Config.sina_user;
	private String password = Config.sina_pwd;
     
	/**
	 * 识别验证码
	 * @param data
	 * @return
	 */
	synchronized public String decryptValiateCode(byte[] data)
	{
		try
		{
			//将验证码写到文件中
//			FileOutputStream output = new FileOutputStream("./img.png");
//			output.write(data);
//			output.flush();
//			output.close();
//			System.out.println("验证码已经打印至"+UUAPI.IMGPATH+",请手工输入：") ;
//			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//			String code = br.readLine();
//			if(code.length()>=3){
//				return code;
//			}
			
//			String result[] = regocgnizer.decryptValiateCode(data, 1005);
//			if (result == null)
//			{
//				return null;
//			}
//			lastCode = result[1];
//			lastImgCodeId = Integer.valueOf(result[0]);
//			System.out.println("this img codeID:" + result[0]);
//			System.out.println("return recongize Result:" + result[1]);
//
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return lastCode;
	}

	/**
	 * 单例的构造函数
	 */
	public DefaultSinaDataUtilis()
	{
		//读取cookies
		BasicCookieStore cookiestore = (BasicCookieStore) Utils.readObject(cookiesFile);
		if (cookiestore != null)
		{
			cookieStore = cookiestore;
		}
		httpClient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).setDefaultCookieStore(cookieStore).build();
		//线程池
		execService = Executors.newFixedThreadPool(2);
		requestExecService = new FutureRequestExecutionService(httpClient, execService);
	}

//
//	static synchronized public DefaultSinaDataUtilis getInstance()
//	{
//		if (instance == null)
//		{
//			instance = new DefaultSinaDataUtilis();
//			if (!instance.init())
//				return null;
//		}
//		return instance;
//	}

	public boolean init()
	{
		if (isLogined)
			return true;
		isLogined = login();
		return isLogined;
	}

	class SinaParameter
	{
		String rsakv = "";
		String servertime = "";
		String pcid = "";
		// String exectime="";
		String nonce = "";
		String pubkey = "";
		// String retcode="";
	}
    //预先登陆新浪，系统默认假定这个登陆可以成功
	private boolean preLogin()
	{
		String callback = "sinaSSOController.preloginCallBack";
		Map<String, String> map = new HashMap<String, String>();

		map.put("_", "1443843093789");
		map.put("callback", callback);
		map.put("client", "ssologin.js(v1.4.18)");
		map.put("entry", "finance");
		map.put("rsakt", "mod");
		map.put("su", "MTg5ODE5OTA1ODY=");

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("login.sina.com.cn").setPath("/sso/prelogin.php").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			// 放入请求头的内容，必须是以键值对的形式
			httpmethod.addHeader("Accept", "application/javascript, */*;q=0.8");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");
			httpmethod.addHeader("Content-Type", "application/x-www-form-urlencoded");
			httpmethod
					.addHeader("Cookie",
							"U_TRS1=00000026.bcc96367.560f4aa4.b581d306;U_TRS2=00000026.bcd46367.560f4aa4.8deba2ba;SUB=_2AkMhU8WZf8NhqwJRmPoQxG_jao1-ww7EiebDAH_sJxJjHlAR7KG13MBOM_ILwWF9GIGRW4wy7kkb;SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9Whqe6l4nGEi3n95oJL6PjbQ");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "login.sina.com.cn");
			httpmethod.addHeader("Referer", "http://i.finance.sina.com.cn/login.html?");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				String body = ret.substring(callback.length() + 1, ret.lastIndexOf(")"));
				Utils.writeObject(cookieStore, cookiesFile);
				this.preLoginPara = this.getPreLoginPara(body);
				getLevel2ClientIpInfo();// 获取level2认证使用的IP地址
				// return getIndexResult(body);
				// print(body);
				System.out.println("pre login sina ok!");
				return true;
			}

		} catch (URISyntaxException e)
		{
			e.printStackTrace();
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		} catch (ExecutionException e)
		{
			e.printStackTrace();
		}
		System.out.println("pre login sina fail!");
		return false;
	}

	private static String encodeAccount(String account)
	{
		String userName = "";
		try
		{
			userName = Base64.encodeBase64String(URLEncoder.encode(account, "UTF-8").getBytes());
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return userName;
	}

	public byte[] getValidateCode()
	{
		try
		{
			String URL = "http://login.sina.com.cn/cgi/pin.php?r=60315573&s=0&p=gz-e56b44fc98bdc8f2a078997d3c79735061d6";
			HttpGet httpget = new HttpGet(URL);

			httpget.addHeader("Accept", "image/webp,*/*;q=0.8");
			httpget.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpget.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpget.addHeader("Connection", "keep-alive");
			httpget.addHeader("DNT", "1");
			httpget.addHeader("Host", "login.sina.com.cn");
			httpget.addHeader("Referer", "http://www.sina.com.cn/");
			httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<byte[]> futur_ret = requestExecService.execute(httpget, HttpClientContext.create(), new BytesResponseHandler());
			byte[] ret = futur_ret.get();
			if (ret != null)
			{
				Utils.writeObject(cookieStore, cookiesFile);
				// Utils.writFile("d:/v.png", ret);
				return ret;
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		return null;
	}

	synchronized private boolean login()
	{
		if (isLogined)
			return true;

		if (!preLogin())
			return false;

		try
		{
			String servertime = preLoginPara.servertime;
			String nonce = preLoginPara.nonce;
			String sin_pk = preLoginPara.pubkey;
			String rsakv = preLoginPara.rsakv;
			String pwdString = servertime + "\t" + nonce + "\n" + password;

			// 加密密码
			String sp = new BigIntegerRSA().rsaCrypt(sin_pk, "10001", pwdString);

			HttpPost httpmethod = new HttpPost("http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)");

			httpmethod.addHeader("Accept", "text/html, application/xhtml+xml, */*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Cache-Control", "no-cache");
			httpmethod.addHeader("Connection", "keep-alive");
			httpmethod.addHeader("Content-Type", "application/x-www-form-urlencoded");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "login.sina.com.cn");
			httpmethod.addHeader("Referer", "http://i.finance.sina.com.cn/login.html?");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			Map<String, String> datas = new HashMap<String, String>();
			// String callback = "parent.sinaSSOController.loginCallBack";

			// datas.put("callback", callback);
			datas.put("encoding", "UTF-8");
			datas.put("entry", "finance");
			datas.put("from", "5");
			datas.put("gateway", "1");
			datas.put("nonce", nonce);

			datas.put("pagerefer", "");
			datas.put("prelt", "prelt");
			datas.put("pwencode", "rsa2");
			datas.put("returntype", "TEXT");
			datas.put("rsakv", rsakv);
			datas.put("savestate", "30");
			datas.put("servertime", servertime);
			datas.put("service", "finance");
			datas.put("setdomain", "1");
			datas.put("sp", sp);

			datas.put("sr", "1920*1080");
			datas.put("su", encodeAccount(username));
			datas.put("useticket", "0");

			List<NameValuePair> nvps = Utils.getParam(datas);

			httpmethod.setEntity(new UrlEncodedFormEntity(nvps));

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// {"retcode":"4049","reason":"\u4e3a\u4e86\u60a8\u7684\u5e10\u53f7\u5b89\u5168\uff0c\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801"}

				// pre login sina ok!
				// reason:为了您的帐号安全，请输入验证码
				// retcode:4049
				// login sina ok!

				int code = getLoginResult(ret);
				switch (code)
				{
				case 0:
					Utils.writeObject(cookieStore, cookiesFile);
					System.out.println("login sina ok!");
					isLogined = true;
					return true;
				case 4049:// 为了您的帐号安全，请输入验证码
					System.out.println("now login with verify code.");
					return this.loginWithVeryCode();
				default:
				}

			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("login sina fail!");
		return false;

	}

	synchronized public boolean loginWithVeryCode()
	{
		if (isLogined)
			return true;

		if (!preLogin())
			return false;

		byte[] d = getValidateCode();
		if (d == null)
			return false;

		String vildCode = decryptValiateCode(d);
		if (vildCode == null)
			return false;

		try
		{
			String servertime = preLoginPara.servertime;
			String nonce = preLoginPara.nonce;
			String sin_pk = preLoginPara.pubkey;
			String rsakv = preLoginPara.rsakv;
			String pwdString = servertime + "\t" + nonce + "\n" + password;

			// 加密密码
			String sp = new BigIntegerRSA().rsaCrypt(sin_pk, "10001", pwdString);

			HttpPost httpmethod = new HttpPost("http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)");

			httpmethod.addHeader("Accept", "text/html, application/xhtml+xml, */*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Cache-Control", "no-cache");
			httpmethod.addHeader("Connection", "keep-alive");
			httpmethod.addHeader("Content-Type", "application/x-www-form-urlencoded");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "login.sina.com.cn");
			httpmethod.addHeader("Referer", "http://i.finance.sina.com.cn/login.html?");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			Map<String, String> datas = new HashMap<String, String>();

			datas.put("entry", "finance");
			datas.put("from", "5");
			datas.put("gateway", "1");
			datas.put("savestate", "30");
			datas.put("useticket", "0");
			datas.put("pagerefer", "http://stock.finance.sina.com.cn/lv2/sh000001.html");
			datas.put("vsnf", "1");
			datas.put("door", vildCode);
			datas.put("su", encodeAccount(username));
			datas.put("service", "sso");
			datas.put("servertime", servertime);
			datas.put("nonce", nonce);
			datas.put("pwencode", "rsa2");
			datas.put("rsakv", rsakv);
			datas.put("sp", sp);
			datas.put("sr", "1920*1080");
			datas.put("encoding", "UTF-8");
			datas.put("cdult", "3");
			datas.put("domain", "sina.com.cn");
			datas.put("prelt", "109");
			datas.put("returntype", "TEXT");

			List<NameValuePair> nvps = Utils.getParam(datas);
			httpmethod.setEntity(new UrlEncodedFormEntity(nvps));
			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// {"retcode":"4049","reason":"\u4e3a\u4e86\u60a8\u7684\u5e10\u53f7\u5b89\u5168\uff0c\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801"}

				// pre login sina ok!
				// reason:为了您的帐号安全，请输入验证码
				// retcode:4049
				// login sina ok!

				int code = getLoginResult(ret);
				switch (code)
				{
				case 0:
					Utils.writeObject(cookieStore, cookiesFile);
					System.out.println("login sina ok!");
					isLogined = true;
					return true;
				case 4049:// 为了您的帐号安全，请输入验证码

					break;
				case 2070:// 输入的验证码不正确"
					System.out.println("输入的验证码不正确");
					reportCodeErr();
					return this.loginWithVeryCode();
				default:
				}

			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("login sina fail!");

		return false;

	}

	public void reportCodeErr()
	{
		regocgnizer.reportError(lastImgCodeId);
	}

	private int getLoginResult(String str)
	{
		JSONObject jsonObject = new JSONObject(str);
		Utils.printJSONObj(jsonObject);
		int retcode = jsonObject.getInt("retcode");
		// String reason = jsonObject.getString("reason");
		return retcode;
	}

	public boolean getRealCJMX()
	{
		// 逐笔
		// http://quotes.money.163.com/service/zhubi_ajax.html?symbol=000011&end=09%3A51%3A52

		// 查询字符串
		// symbol:000011
		// end:09:51:52

		return true;
	}

	// http://market.finance.sina.com.cn/downxls.php?date=2015-10-23&symbol=sz002342

	// 某天的，历史逐笔
	// downloadCJMX，相同
	public Map<String, String> _getHistoryZBInfo(String symbol, String date)
	{
		try
		{
			String daimas = Config.generateCode(symbol);// 单只股票可以这样生成，指数不能

			Map<String, String> map = new HashMap<String, String>();
			map.put("symbol", daimas);
			map.put("date", date);

			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("market.finance.sina.com.cn").setPath("/downxls.php").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "market.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			// System.out.println(httpmethod.getRequestLine());
			HttpRequestFutureTask<byte[]> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new BytesResponseHandler());
			byte[] ret = futur_ret.get();
			if (ret != null)
			{
				getHistoryZBresult(ret);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private void getHistoryZBresult(byte[] bs)
	{
		try
		{
			ByteArrayInputStream in = new ByteArrayInputStream(bs);
			BufferedReader dr = new BufferedReader(new InputStreamReader(in, "GBK"));
			String line = dr.readLine();
			System.out.println("[" + line + "]");
			while ((line = dr.readLine()) != null)
			{
				// String[] str = line.split("\t");
				// for (String s : str)
				// {
				// System.out.print(s + ",");
				// }
				// String code = getEncoding(line);
				// System.out.println("[" + code + "]");
				// String outStr = new String(line.getBytes("UTF-8"), "UTF-8");
				// System.out.println("[" + outStr + "]");

				System.out.println("[" + line + "]");
				line = dr.readLine();
			}
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 当天的，历史逐笔

	public int getTodayZBInfo(List<ZB> zbs, String daimas, String stime, String etime, int page, int mon, int pageNum)
	{
		try
		{

			Map<String, String> map = new HashMap<String, String>();
			map.put("symbol", daimas);
			// map.put("callback", callback);
			map.put("pageNum", pageNum + "");
			map.put("stime", stime);
			map.put("etime", etime);
			// map.put("sign", sign);
			map.put("page", page + "");
			map.put("mon", mon + "");
			// map.put("_", "1444304564027");

			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("stock.finance.sina.com.cn").setPath("/stock/api/openapi.php/StockLevel2Service.getTransactionList").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			// System.out.println(httpmethod.getRequestLine());
			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				return getHistoryZBreuslt(zbs, ret);
			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return -1;
	}

	public List<ZB> getTodayZBInfo(String symbol, String stime, String etime)
	{
		String daimas = Config.generateCode(symbol);// 单只股票可以这样生成，指数不能
		int pageNum = 10000;// 每页返回数量
		int page = 1;// 从1开始

		// String stime = "09:00:00";
		// String etime = "15:30:00";
		int mon = 0;// 每笔成交最小资金

		List<ZB> zbs = new ArrayList<>();
		for (;;)
		{
			int size = getTodayZBInfo(zbs, daimas, stime, etime, page, mon, pageNum);
			if (size < pageNum)
				break;
			page++;
		}

		for (int i = 0; i < zbs.size(); i++)
		{
			ZB zb = zbs.get(i);
			String op = zb.op == ZB.OP_BUY ? "buy" : (zb.op == ZB.OP_SELL ? "sell" : "ping");
			int type = Utils.getMoneyType(zb.price, zb.vol);
			String type_str = "";
			if (type == 0 || type == 1)
			{
				type_str = Utils.getMoneyTypeString(type);
			}
			System.out.println(zb.sortid + "\t" + Utils.msToLongStr(zb.time) + "\t" + zb.price + "\t" + zb.vol + "\t" + op + "\t" + zb.buynum + "\t" + zb.sellnum + "\t" + type_str);
		}

		return zbs;
	}

	public boolean getLevel2ClientIpInfo()
	{
		try
		{
			String list = "sys_clientip";
			Map<String, String> map = new HashMap<String, String>();
			map.put("list", list);

			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("https").setHost("ff.sinajs.cn").setPath("/").setParameters(para).build();

			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "ff.sinajs.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			try
			{
				HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
				String ret = futur_ret.get();
				if (ret != null)
				{
					clientIp = ret.substring(ret.indexOf("=") + 2, ret.length() - 3);
					return true;
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}
  
	public String getNewStockCheckData(List<String> symbols)
	{
		try
		{
			String symbol = "sz002407";
			long now = System.currentTimeMillis();
			String callback = "jQuery111203845195004250854_1447405607433";
			Map<String, String> map = new HashMap<String, String>();
			map.put("symbol", symbol);
			map.put("callback", callback);
			map.put("_", now + "");

			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("vip.stock.finance.sina.com.cn").setPath("/corp/api/openapi.php/CB_AllService.getNewStockCheckData").setParameters(para).build();

			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "vip.stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			for (int i = 0; i < 3; i++)
			{

				try
				{
					HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
					String ret = futur_ret.get();
					if (ret != null)
					{
						System.out.println(ret);
						String response = ret.substring(callback.length() + 4, ret.lastIndexOf(")") - 1);
						return response;
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}

			}

		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public HttpRequestFutureTask<String> doHttpMethod(HttpRequestBase httpmethod)
	{
		return requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
	}

	private List<WeiboRef> getWeiboResult(String str)
	{
		JSONObject jsonObject = new JSONObject(str);
		JSONObject result = jsonObject.getJSONObject("result");

		JSONArray data = result.getJSONArray("data");
		JSONObject status = result.getJSONObject("status");
		int code = status.optInt("code");

		if (code != 0)
		{
			return null;
		}

		List<WeiboRef> list = new ArrayList<>();

		for (int i = 0; i < data.length(); i++)
		{
			JSONObject obj = data.getJSONObject(i);
			// System.out.println("[" + i + "]=" + obj);
			WeiboRef wr = new WeiboRef();
			wr.REF = obj.optLong("REF");
			wr.name = obj.optString("NAME");
			String symbol = obj.optString("SYMBOL").replace("sh", "").replace("sz", "");
			wr.symbol = symbol;
			list.add(wr);
		}

		return list;
	}

	public Level1_ZJLXinfo getLeveL1ZJLXInfos(String symbol)
	{
		List<String> symbols = new ArrayList<>();
		symbols.add(symbol);
		Map<String, Level1_ZJLXinfo> infos = getLeveL1ZJLXInfos(symbols);
		if (infos == null || infos.size() <= 0)
			return null;

		return infos.get(symbol);
	}

	public Map<String, Level1_ZJLXinfo> getLeveL1ZJLXInfos(List<String> symbols)
	{
		Map<String, Level1_ZJLXinfo> mfs = new HashMap<>();
		if (symbols == null || symbols.size() <= 0)
			return mfs;

		try
		{
			// daima:sh600744,sz002594,sz300205,
			// rn:1445908909983
			String daimas = generateCodes(symbols);// 单只股票可以这样生成，指数不能
			Map<String, String> map = new HashMap<String, String>();
			map.put("daima", daimas);
			// map.put("callback", callback);
			map.put("rn", "1445908909983");
			// http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/MoneyFlow.ssi_ssfx_flzjtj
			String url = "http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/MoneyFlow.ssi_ssfx_flzjtj";
			HttpPost httppost = new HttpPost(url);

			httppost.addHeader("Accept", "*/*");
			httppost.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httppost.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httppost.addHeader("Connection", "keep-alive");

			httppost.addHeader("DNT", "1");
			httppost.addHeader("Host", "money.finance.sina.com.cn");

			httppost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			List<NameValuePair> nvps = Utils.getParam(map);
			httppost.setEntity(new UrlEncodedFormEntity(nvps));

			for (int i = 0; i < 3; i++)
			{
				try
				{
					HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httppost, HttpClientContext.create(), new StringResponseHandler());
					String ret = futur_ret.get();
					if (ret != null)
					{
						getLevel1ZJLXreuslt(ret, mfs);
						return mfs;
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return mfs;
	}
    //获取level1资金流量
	private void getLevel1ZJLXreuslt(String str, Map<String, Level1_ZJLXinfo> mfs)
	{
		JSONArray items = new JSONArray(str);
		for (int i = 0; i < items.length(); i++)//
		{
			JSONObject obj = items.getJSONObject(i);

			Level1_ZJLXinfo info = new Level1_ZJLXinfo();
			info.mf[0][0] = obj.optDouble("r0_in");
			info.mf[0][1] = obj.optDouble("r1_in");
			info.mf[0][2] = obj.optDouble("r2_in");
			info.mf[0][3] = obj.optDouble("r3_in");

			info.mf[1][0] = obj.optDouble("r0_out");
			info.mf[1][1] = obj.optDouble("r1_out");
			info.mf[1][2] = obj.optDouble("r2_out");
			info.mf[1][3] = obj.optDouble("r3_out");

			info.symbol = obj.optString("symbol").substring(2);
			info.name = obj.optString("name");
			info.trade = obj.optDouble("trade");//
			info.netamount = obj.optDouble("netamount");
			info.changeratio = obj.optDouble("changeratio");
			info.curr_capital = obj.optDouble("curr_capital");
			info.r0x_ratio = obj.optDouble("r0x_ratio");
			info.turnover = obj.optDouble("turnover");
			info.volume = obj.optDouble("volume");

			info.mf[2][0] = obj.optDouble("r0");// 需要研究下
			info.mf[2][1] = obj.optDouble("r1");
			info.mf[2][2] = obj.optDouble("r2");
			info.mf[2][3] = obj.optDouble("r3");
			mfs.put(info.symbol, info);
		}
	}

	public List<Level2_DapanHistoryZJLXNetInfo> getLevel2DapanHistoryZJLXInfos()
	{
		List<Level2_DapanHistoryZJLXNetInfo> all = new ArrayList<>();
		int num = 10;
		int dpc = 1;
		for (int page = 1;; page++)
		{
			List<Level2_DapanHistoryZJLXNetInfo> list = getLevel2DapanHistoryZJLXInfos(page, num, dpc);
			if (list == null || list.size() <= 0)
			{
				break;
			}
			all.addAll(list);
		}
		return all;
	}

	public List<Level2_DapanHistoryZJLXNetInfo> getLevel2DapanHistoryZJLXInfos(int page, int num, int dpc)
	{
		try
		{
			// String callback="jQuery111206837438934016973_1448345206458";
			// _:14483452

			Map<String, String> map = new HashMap<String, String>();
			map.put("page", page + "");
			map.put("num", num + "");
			map.put("dpc", dpc + "");
			// map.put("callback", callback);

			List<NameValuePair> para = Utils.getParam(map);
			// String var =
			// java.net.URLEncoder.encode("var _sh6000002015","utf-8");
			String var = java.net.URLEncoder.encode("var sh600000", "utf-8");

			URI uri = new URIBuilder().setScheme("http").setHost("stock.finance.sina.com.cn").setPath("/stock/api/openapi.php/StockLevel2Service.getLv2ZhishuRank").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				return getLevel2DapanHistoryZJLXReuslt(ret);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	private List<Level2_DapanHistoryZJLXNetInfo> getLevel2DapanHistoryZJLXReuslt(String str)
	{
		List<Level2_DapanHistoryZJLXNetInfo> list = new ArrayList<>();
		JSONObject jsonObject = new JSONObject(str);
		JSONObject result = (JSONObject) jsonObject.get("result");
		// Utils.printJSONObj(result);
		JSONObject _data = result.optJSONObject("data");
		if (_data == null)
			return null;
		JSONArray data = _data.optJSONArray("data");
		if (data == null)
			return null;
		// Utils.printJSONArray(data);
		for (int i = 0; i < data.length(); i++)
		{
			JSONObject item = data.getJSONObject(i);
			Level2_DapanHistoryZJLXNetInfo history = new Level2_DapanHistoryZJLXNetInfo();
			history.day = Utils.shortStrToDate(item.optString("date")).getTime();
			history.shclose = item.optDouble("shclose");
			history.shzf = item.optDouble("shzf");
			history.szclose = item.optDouble("szclose");
			history.szzf = item.optDouble("szzf");

			double r0_in = item.optDouble("r0_in");
			double r0_out = item.optDouble("r0_out");
			double r1_in = item.optDouble("r1_in");
			double r1_out = item.optDouble("r1_out");
			double r2_in = item.optDouble("r2_in");
			double r2_out = item.optDouble("r2_out");
			double r3_in = item.optDouble("r3_in");
			double r3_out = item.optDouble("r3_out");

			Level2_ZJLXNetInfo info = new Level2_ZJLXNetInfo();
			info.symbol = "dapan";//
			info.net_mf[0] = r0_in - r0_out;// 特大单净流入
			info.net_mf[1] = r1_in - r1_out;// 大单净流入
			info.net_mf[2] = r2_in - r2_out;// 中单净流入
			info.net_mf[3] = r3_in - r3_out;// 小单净流入
			double sum = r0_in + r1_in + r2_in + r3_in;
			info.sum = sum;// 总和，单方向资金
			history.zjlxinfo = info;
			list.add(history);
			// info.print();
		}

		return list;
	}

	public List<Level2_ZJLXNetInfo> getLevel2Stock5dayMinuteZJLXInfos(String symbol)
	{
		try
		{
			// https://stock.sina.com.cn/stock/api/jsonp.php/var%20_sh6005162015=/StockLevel2Service.getLv2A5dayminline?symbol=sh600516&random=$rn
			String code = Config.generateCode(symbol);
			Map<String, String> map = new HashMap<String, String>();
			map.put("random", "$rn");
			map.put("symbol", code);
			List<NameValuePair> para = Utils.getParam(map);
			String var = java.net.URLEncoder.encode("var " + code, "utf-8");
			URI uri = new URIBuilder().setScheme("http").setHost("stock.finance.sina.com.cn").setPath("/stock/api/jsonp.php/" + var + "=/StockLevel2Service.getLv2A5dayminline").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				System.out.println(ret);
				String key = "new String(";
				String body = ret.substring(ret.indexOf(key) + key.length() + 1, ret.lastIndexOf("\"") - 1);
				return getLevel2Stock5dayMinuteZJLXreuslt(symbol, body);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public List<Level2_ZJLXNetInfo> getLevel2Dapan5dayMinuteZJLXInfos()
	{
		try
		{
			Map<String, String> map = new HashMap<String, String>();
			map.put("random", "$rn");
			List<NameValuePair> para = Utils.getParam(map);
			String symbol = "dapan";
			// String var =
			// java.net.URLEncoder.encode("var _sh6000002015","utf-8");
			String var = java.net.URLEncoder.encode("var sh600000", "utf-8");
			URI uri = new URIBuilder().setScheme("http").setHost("stock.finance.sina.com.cn").setPath("/stock/api/jsonp.php/" + var + "=/StockLevel2Service.getLv2ZhiShu5dayminline").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "stock.finance.sina.com.cn");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				String key = "new String(";
				String body = ret.substring(ret.indexOf(key) + key.length() + 1, ret.lastIndexOf("\"") - 1);
				// System.out.println(body);
				return getLevel2Stock5dayMinuteZJLXreuslt(symbol, body);
			}
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private List<Level2_ZJLXNetInfo> getLevel2Stock5dayMinuteZJLXreuslt(String symbol, String str)
	{
		// 2015-11-17|09:30,-732486357.99,-344956731.35,597111821.201,480331268.139|09:31,-1116712369.49,
		List<Level2_ZJLXNetInfo> list = new ArrayList<>();
		for (String day_str : str.split("R"))
		{
			String[] m_data = day_str.split("\\|");
			String day = m_data[0];
			for (int i = 1; i < m_data.length; i++)
			{
				String minuts = m_data[i];
				String[] mfstr = minuts.split(",");
				String time = mfstr[0];
				long info_time = Utils.strToDate(day + " " + time + ":00").getTime();
				Level2_ZJLXNetInfo info = new Level2_ZJLXNetInfo();
				info.symbol = symbol;
				info.time = info_time;
				for (int j = 1; j < mfstr.length; j++)
				{
					String mf = mfstr[j];
					info.net_mf[j - 1] = Double.valueOf(mf);
				}
				list.add(info);
			}
		}

		return list;
	}

	public Level2_ZJLXNetInfo getLevel2DapanZJLXInfos()
	{
		try
		{
			String type = "dapan";// "zhishu";
			String symbol = "sh600000";
			String callback = "inout=";
			Map<String, String> map = new HashMap<String, String>();

			map.put("type", type);
			map.put("symbol", symbol);
			map.put("random", Math.random() + "");
			// map.put("callback", callback);

			List<NameValuePair> para = Utils.getParam(map);
			// http://stock.finance.sina.com.cn/stock/api/openapi.php/StockLevel2Service.getLv2BingList?type=dapan&symbol=sh600000&random=6.576324289897457&callback=inout=
			URI uri = new URIBuilder().setScheme("http").setHost("stock.finance.sina.com.cn").setPath("/stock/api/openapi.php/StockLevel2Service.getLv2BingList").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				return getLevel2DapanZJLXreuslt(ret);
			}
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	public List<Level2_HangyeZJLXNetInfo> getLevel2HangyeZJLXInfos()
	{
		try
		{
			// String callback = "jQuery111209445138988085091_1448248292427";
			int page = 1;
			int num = 400;
			int dpc = 1;
			String type = "";
			Map<String, String> map = new HashMap<String, String>();
			map.put("p", page + "");
			map.put("num", num + "");
			map.put("type", type);
			// map.put("orderby", orderby);
			// map.put("ordertype", ordertype);
			// map.put("callback", callback);
			map.put("dpc", dpc + "");

			// map.put("_", "14482482");

			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("stock.finance.sina.com.cn").setPath("/stock/api/openapi.php/StockLevel2Service.getLv2CateRank").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				return getLevel2HangyeZJLXreuslt(ret);
			}
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	// String type="":全部
	// type=zxqy:中小
	// type=cyb,创业
	// public List<Level2_ZJLXNetInfo> getLevel2ZJLXInfos(String type)
	public List<Level2_ZJLXNetInfo> getLevel2ZJLXMartInfos(String type)
	{
		List<Level2_ZJLXNetInfo> all = new ArrayList<>();
		int num = 400;
		int dpc = 1;
		// String type = "cyb";// type:zxqy,cyb,
		for (int page = 1;; page++)
		{
			List<Level2_ZJLXNetInfo> list = getLevel2ZJLXMartInfos(page, num, dpc, type);
			if (list == null || list.size() <= 0)
			{
				break;
			}
			all.addAll(list);
		}
		return all;
	}

	public List<Level2_ZJLXNetInfo> getLevel2ZJLXMartInfos(int page, int num, int dpc, String type)
	{
		try
		{
			// String callback = "jQuery111209445138988085091_1448248292427";
			Map<String, String> map = new HashMap<String, String>();

			String orderby = "zl_sub";// 按主力流入
			String ordertype = "desc";

			map.put("p", page + "");
			map.put("num", num + "");
			map.put("type", type);
			map.put("orderby", orderby);
			map.put("ordertype", ordertype);
			// map.put("callback", callback);
			map.put("dpc", dpc + "");

			// map.put("_", "14482482");

			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("stock.finance.sina.com.cn").setPath("/stock/api/openapi.php/StockLevel2Service.getLv2ARank").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			// Accept:text/javascript, application/javascript,
			// application/ecmascript, application/x-ecmascript, */*; q=0.01

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				return getLevel2ZJLXMartreuslt(ret);
			}
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	public Map<String, Level2_ZJLXinfo> getLevel2ZJLXInfos(List<String> symbols)
	{
		Map<String, Level2_ZJLXinfo> mfs = new HashMap<>();
		Map<String, HttpRequestFutureTask<String>> futures = new HashMap<>();

		for (String symbol : symbols)
		{
			HttpRequestFutureTask<String> future_ret = getLevel2ZJLXInfo(symbol);
			futures.put(symbol, future_ret);
		}

		for (String symbol : symbols)
		{
			HttpRequestFutureTask<String> future_ret = futures.get(symbol);
			try
			{
				String ret = future_ret.get();
				Level2_ZJLXinfo obj = getLevel2ZJLXreuslt(symbol, ret);
				if (obj != null)
				{
					mfs.put(symbol, obj);
				}
			} catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return mfs;
	}

	public Level2_ZJLXinfo getLevel2ZJLXInfos(String symbol)
	{
		try
		{
			HttpRequestFutureTask<String> future_ret = getLevel2ZJLXInfo(symbol);
			String ret = future_ret.get();
			return getLevel2ZJLXreuslt(symbol, ret);
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// 资金流向,及時，和頁面相同
	private HttpRequestFutureTask<String> getLevel2ZJLXInfo(String symbol)
	{
		try
		{
			String daimas = Config.generateCode(symbol);// 单只股票可以这样生成，指数不能
			// String callback = "inout=";
			double random = Math.random();
			Map<String, String> map = new HashMap<String, String>();
			map.put("symbol", daimas);
			// map.put("callback", callback);
			map.put("random", random + "");

			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("stock.finance.sina.com.cn").setPath("/stock/api/openapi.php/StockLevel2Service.getLv2mfminline").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			return futur_ret;
			// String ret = futur_ret.get();
			// if (ret != null)
			// {
			// // System.out.println(ret);
			// // return getLevel2ZJLXreuslt(ret);
			//
			// }

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private Level2_ZJLXNetInfo getLevel2DapanZJLXreuslt(String str)
	{

		JSONObject jsonObject = new JSONObject(str);
		JSONObject result = (JSONObject) jsonObject.get("result");
		JSONObject item = result.optJSONObject("data");
		if (item == null)
			return null;

		double r0_in = item.optDouble("r0_in");
		double r0_out = item.optDouble("r0_out");
		double r1_in = item.optDouble("r1_in");
		double r1_out = item.optDouble("r1_out");
		double r2_in = item.optDouble("r2_in");
		double r2_out = item.optDouble("r2_out");
		double r3_in = item.optDouble("r3_in");
		double r3_out = item.optDouble("r3_out");

		Level2_ZJLXNetInfo info = new Level2_ZJLXNetInfo();
		info.symbol = "dapan";//
		info.net_mf[0] = r0_in - r0_out;// 特大单净流入
		info.net_mf[1] = r1_in - r1_out;// 大单净流入
		info.net_mf[2] = r2_in - r2_out;// 中单净流入
		info.net_mf[3] = r3_in - r3_out;// 小单净流入
		double sum = r0_in + r1_in + r2_in + r3_in;
		info.sum = sum;// 总和，单方向资金
		// info.print();
		return info;
	}

	private List<Level2_HangyeZJLXNetInfo> getLevel2HangyeZJLXreuslt(String str)
	{
		List<Level2_HangyeZJLXNetInfo> list = new ArrayList<>();

		JSONObject jsonObject = new JSONObject(str);
		JSONObject result = (JSONObject) jsonObject.get("result");
		Utils.printJSONObj(result);
		JSONObject _data = result.optJSONObject("data");
		if (_data == null)
			return null;
		JSONArray items = _data.optJSONArray("data");
		if (items == null)
			return null;
		// Utils.printJSONArray(items);
		for (int i = 0; i < items.length(); i++)
		{
			JSONObject item = items.getJSONObject(i);
			double r0_in = item.optDouble("r0_in");
			double r0_out = item.optDouble("r0_out");
			double r1_in = item.optDouble("r1_in");
			double r1_out = item.optDouble("r1_out");
			double r2_in = item.optDouble("r2_in");
			double r2_out = item.optDouble("r2_out");
			double r3_in = item.optDouble("r3_in");
			double r3_out = item.optDouble("r3_out");
			String category = item.optString("category");

			String name = item.optString("name");
			double sum = item.optDouble("sum");

			Level2_HangyeZJLXNetInfo info = new Level2_HangyeZJLXNetInfo();
			info.name = name;
			info.category = category;
			info.net_mf[0] = r0_in - r0_out;// 特大单净流入
			info.net_mf[1] = r1_in - r1_out;// 大单净流入
			info.net_mf[2] = r2_in - r2_out;// 中单净流入
			info.net_mf[3] = r3_in - r3_out;// 小单净流入
			info.sum = sum;// 总和，单方向资金
			list.add(info);
			// info.print();
		}
		return list;
	}

	private List<Level2_ZJLXNetInfo> getLevel2ZJLXMartreuslt(String str)
	{
		List<Level2_ZJLXNetInfo> list = new ArrayList<>();

		JSONObject jsonObject = new JSONObject(str);
		JSONObject result = (JSONObject) jsonObject.get("result");
		// Utils.printJSONObj(result);
		JSONObject _data = result.optJSONObject("data");
		if (_data == null)
			return null;
		JSONArray data = _data.optJSONArray("data");
		if (data == null)
			return null;
		// Utils.printJSONArray(data);
		for (int i = 0; i < data.length(); i++)
		{
			JSONObject item = data.getJSONObject(i);
			Level2_ZJLXNetInfo info = new Level2_ZJLXNetInfo();
			info.symbol = item.optString("symbol").substring(2);
			// info.main_net_in = item.optLong("zl_sub");// 主力净流入
			info.net_mf[0] = item.optDouble("r0_sub");// 特大单净流入
			info.net_mf[1] = item.optDouble("r1_sub");// 大单净流入
			info.net_mf[2] = item.optDouble("r2_sub");// 中单净流入
			info.net_mf[3] = item.optDouble("r3_sub");// 小单净流入
			info.pricePercent = item.optDouble("zd");// 涨跌幅
			info.sum = item.optLong("s");// 总和，单方向资金
			list.add(info);
			// info.print();
		}

		return list;
	}

	private Level2_ZJLXinfo getLevel2ZJLXreuslt(String symbol, String str)
	{
		// System.out.println(str);
		JSONObject jsonObject = new JSONObject(str);
		JSONObject result = (JSONObject) jsonObject.get("result");
		// JSONObject status = result.getJSONObject("status");
		JSONObject data = result.optJSONObject("data");
		if (data == null)
			return null;

		// for (String key : data.keySet())
		// {
		// Object val = data.get(key);
		// System.out.println("[" + key + "]=" + val);
		// }
		// var
		// moneyFlowData=(({r0_in:20510328.56,r0_out:26245265.96,r1_in:74116697.03,r1_out:62721551.25,r2_in:156258734.73,r2_out:159499931.9,r3_in:164991084.36,r3_out:167410095.57}));

		Level2_ZJLXinfo zjlx = new Level2_ZJLXinfo();
		zjlx.symbol = symbol;
		zjlx.mf = new double[2][4];

		zjlx.mf[0][0] = data.optDouble("r0_in");
		zjlx.mf[0][1] = data.optDouble("r1_in");
		zjlx.mf[0][2] = data.optDouble("r2_in");
		zjlx.mf[0][3] = data.optDouble("r3_in");

		zjlx.mf[1][0] = data.optDouble("r0_out");
		zjlx.mf[1][1] = data.optDouble("r1_out");
		zjlx.mf[1][2] = data.optDouble("r2_out");
		zjlx.mf[1][3] = data.optDouble("r3_out");

		return zjlx;
	}

	public Map<String, Index_zdp> getIndexInfo(List<String> ids)
	{
		String list = "";
		for (String id : ids)
		{
			list += "," + Config.generateCode(id) + "_zdp";
		}
		list.substring(list.indexOf(","));
		try
		{

			String url = "http://hq.sinajs.cn/list=" + list;
			HttpGet httpmethod = new HttpGet(url);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "hq.sinajs.cn");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				return getIndexResult(ret);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private Map<String, Index_zdp> getIndexResult(String str)
	{
		Map<String, Index_zdp> zdps = new HashMap<>();
		String[] lines = str.split(";");
		for (String line : lines)
		{
			line = line.replace("var hq_str", "").replace("_sh", "").replace("_sz", "").replace("\"", "").replace("_zdp", "");
			String[] item = line.split("=");
			if (item.length != 2)
			{
				continue;
			}

			Index_zdp zdp = new Index_zdp();
			zdp.index = item[0];

			String[] counts = item[1].split("=");
			if (counts.length != 3)
			{
				continue;
			}
			for (int i = 0; i < counts.length; i++)
			{
				zdp.count[i] = Integer.valueOf(counts[i]);
			}
			zdps.put(zdp.index, zdp);
		}
		return zdps;
	}

	// 分时成交数据，//分时明细接口
	public Map<String, String> getLevel2FenshiCJMXInfo(String symbol)
	{

		try
		{
			String daimas = Config.generateCode(symbol);// 单只股票可以这样生成，指数不能
			String callback = "jQuery1112009111737669445574_1444305428835";

			Map<String, String> map = new HashMap<String, String>();
			map.put("symbol", daimas);
			// map.put("callback", callback);
			// map.put("_", "1444305428836");

			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("vip.stock.finance.sina.com.cn").setPath("/quotes_service/api/openapi.php/CN_MinlineShot.getMinLineList").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "vip.stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				System.out.println(ret);
				getLevel2FenshiCJMXreuslt(ret);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private void getLevel2FenshiCJMXreuslt(String str)
	{
		JSONObject jsonObject = new JSONObject(str);
		JSONObject result = (JSONObject) jsonObject.get("result");
		JSONArray obj = (JSONArray) result.get("data");

		for (int i = 0; i < obj.length(); i++)
		{
			System.out.println("----------------");
			JSONObject item = obj.getJSONObject(i);
			for (String key : item.keySet())
			{
				Object val = item.get(key);
				System.out.println("[" + key + "]=" + val);
			}
		}

		// for (String key : data.keySet())
		// {
		// Object val = data.get(key);
		// System.out.println("[" + key + "]=" + val);
		// }
	}

	public boolean downloadHistoryCJMX(String symbol, String date, String filename)
	{
		byte[] ret = downloadCJMX(date, symbol);
		if (ret != null)
		{
			Utils.writFile(filename, ret);
			// Utils.parseExcel(filename);
			return true;
		}
		return false;
	}

	public byte[] downloadCJMX(String date, String symbol)
	{
		try
		{
			String code = Config.generateCode(symbol);
			// http://market.finance.sina.com.cn/downxls.php?date=2015-09-07&symbol=sz002268
			String URL = "http://market.finance.sina.com.cn/downxls.php?date=" + date + "&symbol=" + code;
			HttpGet httpmethod = new HttpGet(URL);

			// 放入请求头的内容，必须是以键值对的形式
			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");
			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "market.finance.sina.com.cn");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<byte[]> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new BytesResponseHandler());
			byte[] ret = futur_ret.get();
			if (ret != null)
			{
				return ret;
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		return null;
	}

	public FutureTask<Boolean> asynDownloadCJMX(String date, String symbol, String filename)
	{
		try
		{
			String code = Config.generateCode(symbol);
			// http://market.finance.sina.com.cn/downxls.php?date=2015-09-07&symbol=sz002268
			String URL = "http://market.finance.sina.com.cn/downxls.php?date=" + date + "&symbol=" + code;
			HttpGet httpmethod = new HttpGet(URL);

			// 放入请求头的内容，必须是以键值对的形式
			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");
			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "market.finance.sina.com.cn");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<Boolean> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new DownloadFileResponseHandler(httpmethod, filename));

			return futur_ret;

			// Boolean ret = futur_ret.get();
			// if (ret != null)
			// {
			// }
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub

		return null;
	}

	public JSONObject getSubscribeInfo()
	{
		// matchId:1
		// subSid:1778730363

		Map<String, String> map = new HashMap<String, String>();
		map.put("matchId", "0");
		map.put("subSid", "1778730363");

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("jiaoyi.sina.com.cn").setPath("/api/openapi.php/Subscribe_Service.batchIsSub").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			// charset:utf-8

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "jiaoyi.sina.com.cn");

			httpmethod.addHeader("Referer", "http://jiaoyi.sina.com.cn/proxy/iframe/v1.2.html?proxy_http://jiaoyi.sina.com.cn/proxy/iframe/v1.2.html");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			// HttpResponse httpResponse = httpCient.execute(httpmethod);
			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				System.out.println(ret);
				// return getIndexResult(body);
				print(ret);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public JSONObject getStockHoldInfo(String sid, String cid, int count)
	{
		// String sid = "1778730363";// 2880259462";
		// String cid = "10000";// "100032";
		// int count = 10;

		Map<String, String> map = new HashMap<String, String>();
		map.put("sid", sid);
		map.put("cid", cid);
		map.put("count", count + "");

		String callback = "jsonp_1443846858944_14820008";

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			// http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_1443846858944_14820008/Stockhold_Service.getStockhold
			URI uri = new URIBuilder().setScheme("http").setHost("jiaoyi.sina.com.cn").setPath("/api/jsonp_v2.php/" + callback + "/Stockhold_Service.getStockhold").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "jiaoyi.sina.com.cn");

			// httpmethod.addHeader("Referer",
			// "http://jiaoyi.sina.com.cn/proxy/iframe/v1.2.html?proxy_http://jiaoyi.sina.com.cn/proxy/iframe/v1.2.html");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			// HttpResponse httpResponse = httpCient.execute(httpmethod);
			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				String body = ret.substring(callback.length() + 2, ret.lastIndexOf(")") - 1);
				// return getIndexResult(body);
				return printStockHold(body);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public JSONObject getHistoryTradeInfo(String sid, String cid, String sdate, String edate, int from, int count)
	{

		int sort = 1;

		Map<String, String> map = new HashMap<String, String>();
		map.put("sid", sid);
		map.put("cid", cid);
		map.put("from", from + "");
		map.put("count", count + "");

		map.put("sdate", sdate + "");
		map.put("edate", edate + "");

		map.put("sort", sort + "");

		String callback = "jsonp_1443857369871_61132126";

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			// http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_1443857369871_61132126/Statement_Service.getStatement

			URI uri = new URIBuilder().setScheme("http").setHost("jiaoyi.sina.com.cn").setPath("/api/jsonp_v2.php/" + callback + "/Statement_Service.getStatement").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "jiaoyi.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			// HttpResponse httpResponse = httpCient.execute(httpmethod);
			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				String body = ret.substring(callback.length() + 2, ret.lastIndexOf(")") - 1);
				// return getIndexResult(body);
				return printHistoryTradeInfo(body);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public JSONObject getQueryInfo(int page, int count, String type, String sort, int order)
	{
		// int page=1;//start from 1;
		// int count=40;
		// String type="zxqy";//cyb：创业板,zxqy:中小板，hs_a：全部A股，dpzs：大盘指数
		// int order=0;//0:降序，1升序
		// String sort="changepercent";//trade:当前价格,changepercent:涨跌幅度

		String __s = "[[\"hq\",\"" + type + "\",\"" + sort + "\"," + order + "," + page + "," + count + "]]";
		String callback = "FDC_DC.theTableData";

		// __s:[["hq","cyb","trade",0,9,40]]
		// callback:FDC_DC.theTableData

		Map<String, String> map = new HashMap<String, String>();
		map.put("__s", __s);
		map.put("callback", callback);

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			// http://money.finance.sina.com.cn/d/api/openapi_proxy.php/
			// http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_1443857369871_61132126/Statement_Service.getStatement

			URI uri = new URIBuilder().setScheme("http").setHost("money.finance.sina.com.cn").setPath("/d/api/openapi_proxy.php/").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "money.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);

				String body = ret.substring(ret.indexOf(callback) + callback.length() + 2, ret.lastIndexOf(")") - 1);
				// System.out.println(body);
				return getQueryResult(body);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 按概念跟踪资金流向,查看当前资金流向了哪几个概念 int page=1;//start from 1; int num=20; int
	 * asc=0;//0:降序，1升序 int *
	 * sort="avg_changeratio";//netamount：按净流入资金数量排序，ratioamount：净流入率排序，
	 * avg_changeratio：按涨幅排序
	 */

	public JSONArray getMoneyFlowInfo_Concept(int page, int num, int asc, String sort)
	{
		// int fenlei=0;//fenlei=0：按新浪板块定义分类，fenlei:2：按证监会定义板块分类，fenlei:1按概念板块分类
		int fenlei = 1;
		return getMoneyFlowInfo(page, num, asc, fenlei, sort);
	}

	/**
	 * 按板块跟踪资金流向,查看当前资金流向了哪几个板块 int page=1;//start from 1; int num=20; int
	 * asc=0;//0:降序，1升序 int *
	 * sort="avg_changeratio";//netamount：按净流入资金数量排序，ratioamount：净流入率排序，
	 * avg_changeratio：按涨幅排序
	 */

	public JSONArray getMoneyFlowInfo_Bankuai(int page, int num, int asc, String sort)
	{
		// int fenlei=0;//fenlei=0：按新浪板块定义分类，fenlei:2：按证监会定义板块分类，fenlei:1按概念板块分类
		int fenlei = 0;
		return getMoneyFlowInfo(page, num, asc, fenlei, sort);
	}

	public JSONArray getMoneyFlowInfo(int page, int num, int asc, int fenlei, String sort)
	{
		// int page=1;//start from 1;
		// int num=20;
		// int asc=0;//0:降序，1升序
		// int fenlei=0;//fenlei=0：按新浪板块定义分类，fenlei:2：按证监会定义板块分类，fenlei:1按概念板块分类
		// String
		// sort="avg_changeratio";//netamount：按净流入资金数量排序，ratioamount：净流入率排序，avg_changeratio：按涨幅排序

		Map<String, String> map = new HashMap<String, String>();
		map.put("page", page + "");
		map.put("num", num + "");
		map.put("asc", asc + "");
		map.put("fenlei", fenlei + "");
		map.put("sort", sort);

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			// http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/MoneyFlow.ssl_bkzj_bk

			URI uri = new URIBuilder().setScheme("http").setHost("money.finance.sina.com.cn").setPath("/quotes_service/api/json_v2.php/MoneyFlow.ssl_bkzj_bk").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "money.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				return getMoneyFlowResult(ret);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取该板块下的个股，按板块跟踪资金流向
	 * 
	 * int page = 1;// start from 1; int num = 5; // int asc = 0;// * 0:降序，1升序
	 * // String bankuai = "";//,为空时，所有板块，"0/new_fjzz";//
	 * fenlei=0：按新浪板块定义分类，fenlei:2：按证监会定义板块分类，fenlei:1按概念板块分类 // String sort =
	 * "r0_ratio"
	 * ;//symbol：按代码排序，changeratio，按涨幅排序，turnover，按换手率，netamount：按净流入排序
	 * ，ratioamount：净流入率排序，r0_ratio：主力净流入率排序 // String shichang = "";//市场，sh，sz
	 */

	public JSONArray getBankuaiMoneyFlowStocks(int page, int num, int asc, String bankuai, String shichang, String sort)
	{

		// int page = 1;// start from 1;
		// int num = 5;
		// int asc = 0;// 0:降序，1升序
		// String bankuai = "";//,为空时，所有板块，"0/new_fjzz";//
		// fenlei=0：按新浪板块定义分类，fenlei:2：按证监会定义板块分类，fenlei:1按概念板块分类
		// String sort = "r0_ratio";//
		// symbol：按代码排序，changeratio，按涨幅排序，turnover，按换手率，netamount：按净流入排序，ratioamount：净流入率排序，r0_ratio：主力净流入率排序
		// String shichang = "";

		Map<String, String> map = new HashMap<String, String>();
		map.put("page", page + "");
		map.put("num", num + "");
		map.put("asc", asc + "");
		map.put("bankuai", bankuai);
		map.put("shichang", shichang);
		map.put("sort", sort);

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			// http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/MoneyFlow.ssl_bkzj_ssggzj

			URI uri = new URIBuilder().setScheme("http").setHost("money.finance.sina.com.cn").setPath("/quotes_service/api/json_v2.php/MoneyFlow.ssl_bkzj_ssggzj").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "money.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				return getBankuaiMoneyFlowStockResult(ret);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public List<Level2RankInfo> getChangeRankingList(int count, double min_percent)
	{
		int page = 1;
		int asc = 0;// "desc"
		List<Level2RankInfo> stocks = new ArrayList<>();

		for (;;)
		{
			try
			{
				List<Level2RankInfo> list = getChangeRankingList(page, count, asc);
				if (list == null || list.size() <= 0)
					return stocks;

				for (int i = 0; i < list.size(); i++)
				{
					Level2RankInfo stock = list.get(i);
					if (stock.changepercent < min_percent)
						return stocks;

					stocks.add(stock);
					// boolean isSTstock=stock.name.toUpperCase().contains("S");
					// if(Utils.isLimitup(stock.low,stock.lastclose,isSTstock))
					// {
					//
					// }
				}
				page++;

			} catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
				break;
			}
		}

		return stocks;
	}

	public List<Level2RankInfo> getChangeRankingList(int page, int num, int asc)
	{
		String symbol = "";
		// String callback = "jQuery111206097342136781663_1447161846888";
		Map<String, String> map = new HashMap<String, String>();
		map.put("page", page + "");
		map.put("num", num + "");
		map.put("asc", asc + "");
		map.put("sort", "changepercent");
		map.put("node", "hs_a");
		map.put("_s_r_a", "page");
		// map.put("callback", callback);
		map.put("symbol", symbol);
		map.put("_", "14471622");
		map.put("dpc", "1");

		// Referer:http://stock.finance.sina.com.cn/stock/lv2index.php
		//

		try
		{
			List<NameValuePair> para = Utils.getParam(map);

			URI uri = new URIBuilder().setScheme("http").setHost("vip.stock.finance.sina.com.cn").setPath("/quotes_service/api/openapi.php/Market_Center.getHQNodeData").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "vip.stock.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				return getRankingListResult(ret);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private List<Level2RankInfo> getRankingListResult(String str)
	{
		List<Level2RankInfo> list = new ArrayList<>();

		JSONObject json = new JSONObject(str);
		JSONObject result = json.getJSONObject("result");
		JSONArray items = result.getJSONArray("data");
		for (int i = 0; i < items.length(); i++)
		{
			// System.out.println("--------------------------------" + i);
			JSONObject data = items.getJSONObject(i);
			// Utils.printJSONObj(data);

			Level2RankInfo info = new Level2RankInfo();
			info.name = data.optString("name");
			info.code = data.optString("code");
			info.symbol = data.optString("symbol");
			info.symbol = info.code;

			info.amount = data.optLong("amount");

			info.price = data.optDouble("trade");
			info.changepercent = data.optDouble("changepercent") / 100.0;
			info.turnoverratio = data.optDouble("turnoverratio") / 100.0;
			info.nmc = data.optDouble("nmc") * 10000;// 流通
			info.mktcap = data.optDouble("mktcap") * 10000;// 市值
			info.buy = data.optDouble("buy");
			info.sell = data.optDouble("sell");
			info.ticktime = data.optString("ticktime");
			info.pricechange = data.optDouble("pricechange");
			info.lastclose = data.optDouble("settlement");
			info.volume = data.optLong("volume");
			info.high = data.optDouble("high");
			info.pb = data.optDouble("pb");

			info.price = data.optLong("trade");
			info.low = data.optDouble("low");
			info.per = data.optInt("per");
			info.open = data.optLong("open");
			list.add(info);
		}
		return list;
	}

	/**
	 * 获取指定代码股票的资金流向 在正常情况下，实时数据会有5-10分钟的延迟，我们将每个时间段的数据分别计算并汇总，
	 */

	public JSONObject getStockMoneyFlowInfo(String daima)
	{
		// String daima="sh600893";
		Map<String, String> map = new HashMap<String, String>();
		map.put("daima", daima);

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			// http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/MoneyFlow.ssi_ssfx_flzjtj
			URI uri = new URIBuilder().setScheme("http").setHost("money.finance.sina.com.cn").setPath("/quotes_service/api/json_v2.php/MoneyFlow.ssi_ssfx_flzjtj").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "money.finance.sina.com.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				String body = ret.substring(ret.indexOf("(") + 1, ret.lastIndexOf(")"));
				// System.out.println(body);
				return getStockMoneyFlowResult(body);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 
	 * 获取某个月内的分时曲线数据
	 */

	public JSONObject getStockFenshiInfo(String daima)
	{

		String code = Config.generateCode(daima);
		try
		{
			String url = "http://finance.sina.com.cn/realstock/company/" + code + "/hisdata/2014/04.js";
			HttpGet httpmethod = new HttpGet(url);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "finance.sina.com.cn");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				getFenshiResult(ret);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private Map<String, String> getFenshiResult(String str)
	{
		Map<String, String> map = new HashMap<>();
		for (String s : str.split(";"))
		{
			s = s.trim();
			if (s.equals(""))
			{
				continue;
			}
			System.out.println(s);

			String[] a = s.split("=");
			if (a.length < 2 || !a[0].startsWith("var"))
			{
				continue;
			}

			String levels = a[1].substring(1, a[1].length() - 1);

			System.out.println(levels);

			// 不知道解码出来后怎么使用
			// byte[] out = Base64.decodeBase64(levels);
			// Utils.writFile("f:/1.data", out);
			// System.out.println(Utils.detect(out));
			// System.out.println(new String(out));
		}

		return map;
	}

	String generateCodes(Collection<String> ids)
	{
		String str = "";
		for (String id : ids)
		{
			str += "," + Config.generateCode(id);
		}
		return str.substring(str.indexOf(","));
	}

	// 2cn_sh000001=上证指数,15:09:38,2015-10-16,3338.0730,3358.2972,3393.0178,3334.8539,3391.3516,,0,395460575,459447813308.300,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
	// 2cn_sz399001=深证成指,15:05:02,2015-10-16,11229.3801,11301.9359,11384.2406,11172.0427,11374.8345,,10536012,18028363914,262517434059.370,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
	// 2cn_sh000300=沪深300,15:09:38,2015-10-16,3486.8150,3508.5177,3537.5387,3487.1044,3534.0653,,0,208964709,252211491385.800,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
	// 2cn_sz399005=中小板指,15:05:02,2015-10-16,7628.3456,7674.2905,7719.9977,7557.4572,7710.4684,,2220756,3003427123,56401124574.060,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
	// 2cn_sz399006=创业板指,15:05:02,2015-10-16,2404.5334,2424.6208,2452.9403,2401.0933,2449.0300,,1717098,2212893417,59776204792.210,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,


	private String getQueryCodes(Collection<String> ids)
	{
		String str = "";
		for (String id : ids)
		{
			str += "," + "s_" + Config.generateCode(id);
		}
		return str.substring(str.indexOf(","));
	}

	public SimpleRealInfo getSimpleRealLevelInfo(String symbol)
	{
		List<String> symbols = new ArrayList<>();
		symbols.add(symbol);
		Map<String, SimpleRealInfo> infos = getSimpleRealLevelInfo(symbols);
		if (infos == null || infos.size() <= 0)
			return null;

		return infos.get(symbol);
	}

	public Map<String, SimpleRealInfo> getSimpleRealLevelInfo(Collection<String> symbols)
	{
		String querycodes = getQueryCodes(symbols);// 单只股票可以这样生成，指数不能
		try
		{
			String url = "http://hq.sinajs.cn/list=" + querycodes;
			HttpGet httpmethod = new HttpGet(url);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "hq.sinajs.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			for (int i = 0; i < 3; i++)
			{
				try
				{
					HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
					String ret = futur_ret.get();
					if (ret != null)
					{
						// System.out.println(ret);
						return getSimpleLevelResult(ret);
					}
				} catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private Map<String, SimpleRealInfo> getSimpleLevelResult(String str)
	{
		Map<String, SimpleRealInfo> map = new HashMap<>();
		for (String s : str.split(";"))
		{
			s = s.trim();
			if (s.equals(""))
			{
				continue;
			}
			// System.out.println(s);

			String[] a = s.split("=");
			int startIndex = a[0].lastIndexOf("_");
			if (startIndex < 0)
			{
				continue;
			}
			SimpleRealInfo info = new SimpleRealInfo();
			String daima = a[0].substring(startIndex + 1);
			String levels = a[1].substring(1, a[1].length() - 1);
			// var hq_str_s_sh600797=
			// "浙大网新,14.04,0.56,4.15,728973,100243";

			String[] levelInfo = levels.split(",");
			if (levelInfo.length < 6)
				continue;

			info.symbol = daima.substring(2);
			map.put(info.symbol, info);
			info.name = levelInfo[0];
			info.price = Double.valueOf(levelInfo[1]);
			info.priceDelta = Double.valueOf(levelInfo[2]);
			info.percent = Double.valueOf(levelInfo[3]) / 100.0;
			info.volume = Long.valueOf(levelInfo[4]) * 100;// 成交量，手
			info.amount = Double.valueOf(levelInfo[5]) * 10000;// 成交量，万

			// System.out.println(code + " " +
			// name+","+curPrice+","+percent+"%");

		}

		return map;
	}

	public Level getRealLevelInfo(String symbol)
	{
		List<String> symbols = new ArrayList<>();
		symbols.add(symbol);
		Map<String, Level> infos = getRealLevelInfo(symbols);
		if (infos == null || infos.size() <= 0)
			return null;

		return infos.get(symbol);
	}

	public Map<String, Level> getRealLevelInfo(Collection<String> symbols)
	{
		String daimas = generateCodes(symbols);// 单只股票可以这样生成，指数不能
		try
		{
			String url = "http://hq.sinajs.cn/list=" + daimas;
			HttpGet httpmethod = new HttpGet(url);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "hq.sinajs.cn");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				return getLevelResult(ret);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public String getClientip()
	{
		return clientIp;
	}

	public boolean isLogined()
	{
		return isLogined;
	}

	public void setLogined(boolean logined)
	{
		isLogined = logined;
	}

	String Etag = null;

	public Map<String, String> getRealLevel2Info(List<String> symbols)
	{
		String daimas = generateCodes(symbols);// 单只股票可以这样生成，指数不能
		try
		{
			// URL:http://hq.sinajs.cn/etag.php?_=1444699099648&list=sz300480

			long now = System.currentTimeMillis();
			String url = "http://hq.sinajs.cn/etag.php?_=" + now + "&list=" + daimas;
			HttpGet httpmethod = new HttpGet(url);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "hq.sinajs.cn");
			// if (Etag != null)
			// {
			// httpmethod.addHeader("If-None-Match", Etag);
			// // If-None-Match:W/"ICiAAVWRYuz"
			// }

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<HttpResult> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new ResultResponseHandler());
			HttpResult ret = futur_ret.get();
			if (ret != null)
			{
				for (Header h : ret.headers)
				{
					if (h.getName().equals("Etag"))
					{
						System.out.println(h.getValue());
						Etag = h.getValue();
						break;
					}
				}
				System.out.println(ret.retstring);
				// return getLevelResult(ret);

			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private int getHistoryZBreuslt(List<ZB> zbs, String str)
	{

		JSONObject jsonObject = new JSONObject(str);
		JSONObject result = (JSONObject) jsonObject.get("result");
		JSONObject data = (JSONObject) result.get("data");
		if (data == null)
			return 0;

		int count = data.getInt("count");
		if (count <= 0)
			return 0;

		JSONArray obj = (JSONArray) data.opt("data");
		if (obj == null)
			return 0;

		String date = Utils.getTodayStr();

		for (int i = 0; i < obj.length(); i++)
		{
			// System.out.println("----------------");
			JSONObject item = obj.getJSONObject(i);
			// for (String key : item.keySet())
			// {
			// Object val = item.get(key);
			// System.out.println("[" + key + "]=" + val);
			// }

			double volume = item.optDouble("volume") * 100;// 成交股数
			long buynum = item.getLong("buynum");
			long sellnum = item.getLong("sellnum");
			// long intticktime = item.getLong("intticktime");
			int iotype = item.getInt("iotype");
			String ticktime = item.getString("ticktime");
			double trade = item.optDouble("trade");
			long id = item.getLong("id");

			// String symbol = item.getString("symbol");
			// int tradechannel = item.getInt("tradechannel");

			ZB zb = new ZB();
			String time = date + " " + ticktime;
			zb.time = Utils.longstrToDate(time).getTime();
			zb.price = trade;
			zb.vol = (long) volume;
			zb.buynum = buynum;
			zb.sellnum = sellnum;
			zb.sortid = id;

			zb.op = iotype == 2 ? ZB.OP_BUY : (iotype == 0 ? ZB.OP_SELL : ZB.OP_PING);

			zbs.add(zb);
			// String op = zb.op == ZB.OP_BUY ? "buy" : (zb.op == ZB.OP_SELL ?
			// "sell" : "ping");

			// int type = Utils.getMoneyType(zb.price, zb.num);
			// String type_str = "";
			// if (type == 0 || type == 1)
			// {
			// type_str = Utils.getMoneyTypeString(type);
			// }
			//
			// System.out.println("[" + i + "]:" + Utils.msToLongStr(zb.time) +
			// "\t" + zb.price + "\t" + zb.num + "\t" + op + "\t" + type_str);
		}

		return obj.length();
	}

	private Map<String, Level> getLevelResult(String str)
	{
		Map<String, Level> map = new HashMap<>();
		for (String s : str.split(";"))
		{
			s = s.trim();
			if (s.equals(""))
			{
				continue;
			}
			String[] a = s.split("=");
			int startIndex = a[0].lastIndexOf("_");
			if (startIndex < 0)
			{
				continue;
			}
			Level l = new Level();

			String daima = a[0].substring(startIndex + 1);
			String levels = a[1].substring(1, a[1].length() - 1);

			l.symbol = daima.substring(2);
			String[] levelInfo = levels.split(",");
			l.name = levelInfo[0];

			l.open = Double.valueOf(levelInfo[1]);
			l.lastclose = Double.valueOf(levelInfo[2]);

			l.price = Double.valueOf(levelInfo[3]);
			l.high = Double.valueOf(levelInfo[4]);
			l.low = Double.valueOf(levelInfo[5]);

			// String ?? = levelInfo[6];//???
			// String ?? = levelInfo[7];//???

			l.volume = Double.valueOf(levelInfo[8]);// 成交量，股数
			l.amount = Double.valueOf(levelInfo[9]);// 成交额，元

			l.bidvol1 = Long.valueOf(levelInfo[10]);
			l.bidvol2 = Long.valueOf(levelInfo[12]);
			l.bidvol3 = Long.valueOf(levelInfo[14]);
			l.bidvol4 = Long.valueOf(levelInfo[16]);
			l.bidvol5 = Long.valueOf(levelInfo[18]);

			l.bid1 = Double.valueOf(levelInfo[11]);
			l.bid2 = Double.valueOf(levelInfo[13]);
			l.bid3 = Double.valueOf(levelInfo[15]);
			l.bid4 = Double.valueOf(levelInfo[17]);
			l.bid5 = Double.valueOf(levelInfo[19]);

			l.askvol1 = Long.valueOf(levelInfo[20]);
			l.askvol2 = Long.valueOf(levelInfo[22]);
			l.askvol3 = Long.valueOf(levelInfo[24]);
			l.askvol4 = Long.valueOf(levelInfo[26]);
			l.askvol5 = Long.valueOf(levelInfo[28]);

			l.ask1 = Double.valueOf(levelInfo[21]);
			l.ask2 = Double.valueOf(levelInfo[23]);
			l.ask3 = Double.valueOf(levelInfo[25]);
			l.ask4 = Double.valueOf(levelInfo[27]);
			l.ask5 = Double.valueOf(levelInfo[29]);
			String time = levelInfo[30] + " " + levelInfo[31];
			// System.out.println(time);
			l.time = Utils.strToDate(time).getTime();
			map.put(l.symbol, l);
		}

		return map;
	}

	public JSONObject getHqInfo(String sid, String ids)
	{

		// String sid = "1778730363";// 2880259462";
		// String ids = "69974";// "100032";

		Map<String, String> map = new HashMap<String, String>();
		map.put("sid", sid);
		map.put("ids", ids);

		String callback = "jsonp_1443852236461_59889118";

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			// http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_1443846858944_14820008/Stockhold_Service.getStockhold
			// http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_1443852236461_59889118/Stockhold_Service.getHqInfo
			URI uri = new URIBuilder().setScheme("http").setHost("jiaoyi.sina.com.cn").setPath("/api/jsonp_v2.php/" + callback + "/Stockhold_Service.getHqInfo").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "jiaoyi.sina.com.cn");

			// httpmethod.addHeader("Referer",
			// "http://jiaoyi.sina.com.cn/proxy/iframe/v1.2.html?proxy_http://jiaoyi.sina.com.cn/proxy/iframe/v1.2.html");

			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			// HttpResponse httpResponse = httpCient.execute(httpmethod);
			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				String body = ret.substring(callback.length() + 1, ret.lastIndexOf(")"));
				System.out.println(body);
				printHqinfo(body);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * //获取市场的微博热力指数 market:sh/sz
	 */
	public List<MarketWeiboRef> getMarketWeiboHotInfo(String market)
	{
		String type = "CN";
		String callback = "var%20BO=";
		Map<String, String> map = new HashMap<String, String>();
		map.put("type", type);
		map.put("mkt", market);
		map.put("callback", callback);

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("data.finance.sina.com.cn").setPath("/api/openapi.php/WeiboReferService.getRefMkt").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "data.finance.sina.com.cn");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
			String ret = futur_ret.get();
			if (ret != null)
			{
				// System.out.println(ret);
				String body = ret.substring(ret.indexOf("=(") + 2, ret.lastIndexOf(")"));
				// System.out.println(body);
				return getMarketWeiboResult(body, market);
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private List<MarketWeiboRef> getMarketWeiboResult(String str, String market)
	{
		JSONObject jsonObject = new JSONObject(str);
		JSONObject result = jsonObject.getJSONObject("result");

		JSONArray data = result.getJSONArray("data");
		JSONObject status = result.getJSONObject("status");
		int code = status.optInt("code");

		// for (String key : jsonObject.keySet())
		// {
		// Object val = jsonObject.get(key);
		// System.out.println("[" + key + "]=" + val);
		// }

		if (code != 0)
		{
			return null;
		}
		List<MarketWeiboRef> list = new ArrayList<>();

		for (int i = 0; i < data.length(); i++)
		{
			JSONObject obj = data.getJSONObject(i);
			// System.out.println("[" + i + "]=" + obj);
			MarketWeiboRef wr = new MarketWeiboRef();
			wr.REF = obj.optLong("REF");
			wr.market = market;
			String dt = obj.optString("DT");
			wr.time = Utils.shortStrToDate(dt).getTime();
			list.add(wr);
		}

		return list;

	}

	public JSONObject fastQueryInfo(int page, int num, long max_MCAP, double min_percent, double maxPrice, String sort, String asc)
	{

		// http://screener.finance.sina.com.cn/znxg/view/doViewCsv.php?
		// page=1&num=20&sort=&asc=0&
		// field0=stocktype&field1=sinahy&
		// field2=diyu&value0=*&value1=*&value2=*&
		// field3=mgsy&max3=1.5&min3=0.2&
		// field4=financialratios59&max4=30&min4=3&
		// field5=ltag&max5=29405529.3904&min5=1020&
		// field6=ssmcap&max6=1473490908140&min6=99999999

		Map<String, String> map = new HashMap<String, String>();
		map.put("page", page + "");
		map.put("num", num + "");
		map.put("sort", sort);// sort:changepercent//可按某项排序
		map.put("asc", asc);

		map.put("field0", "stocktype");
		map.put("field1", "sinahy");
		map.put("field2", "diyu");

		map.put("value0", "*");
		map.put("value1", "*");
		map.put("value2", "*");

		map.put("field3", "changepercent");
		map.put("max3", "10.1");
		map.put("min3", (min_percent * 100) + "");

		// long max_MCAP = 300 * 10000 * 10000L;// 最大流通市值
		map.put("field4", "ssmcap");// hs
		map.put("max4", max_MCAP + "");
		map.put("min4", "100000000");

		// double maxPrice = 60;// 60元以下的
		map.put("field4", "trade");// hs
		map.put("max4", maxPrice + "");
		map.put("min4", "1.0");

		// 每股收益
		// field3:mgsy_t
		// max3:9.0946
		// min3:-0.8975

		// map.put("field5", "ssturnover");//hs
		// map.put("max5", "100");
		// map.put("min5", "0");

		// page:1
		// num:20
		// sort:changepercent
		// asc:0
		// field0:stocktype
		// field1:sinahy
		// field2:diyu
		// value0:*
		// value1:*
		// value2:*

		// field3:changepercent
		// max3:10.06
		// min3:7

		// field4:ltag
		// max4:3000000
		// min4:1020

		try
		{
			String url = "http://screener.finance.sina.com.cn/znxg/data/json.php/SSCore.doView";
			HttpPost httpmethod = new HttpPost(url);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "screener.finance.sina.com.cn");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

			List<NameValuePair> nvps = Utils.getParam(map);
			httpmethod.setEntity(new UrlEncodedFormEntity(nvps));

			for (int i = 0; i < 3; i++)
			{
				try
				{
					HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
					String ret = futur_ret.get();
					if (ret != null)
					{
						// System.out.println(ret);
						String body = ret.substring(ret.indexOf("(") + 1, ret.lastIndexOf(")"));
						// System.out.println(body);
						JSONObject jsonObject = new JSONObject(body);
						// for (String key : jsonObject.keySet())
						// {
						// Object val = jsonObject.get(key);
						// System.out.println("[" + key + "]=" + val);
						// }
						JSONArray list = jsonObject.optJSONArray("items");
						if (list != null)
						{
							return jsonObject;
						}
					}
				} catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public List<String> getConditionStocks(int count, long max_MCAP, double min_percent)
	{
		int page = 1;
		// boolean end = false;
		String asc = "0";// "desc"
		String sort = "changepercent";
		double maxPrice = 60;
		// double min_MFSUM=-3000.0;
		List<String> ids = new ArrayList<>();

		for (;;)
		{
			try
			{
				JSONObject jsonObject = fastQueryInfo(page, count, max_MCAP, min_percent, maxPrice, sort, asc);
				if (jsonObject == null)
					break;

				JSONArray list = jsonObject.optJSONArray("items");
				if (list == null)
					break;
				int pagecount = jsonObject.optInt("page_total");
				// System.out.println("pagecount:" + pagecount);

				for (int i = 0; i < list.length(); i++)
				{
					JSONObject stock = (JSONObject) list.get(i);

					// System.out.println(stock);
					// double MFSUM = stock.optDouble("MFSUM");
					// double PE = stock.optDouble("PE");
					// long MCAP = stock.optLong("ssmcap");
					String SNAME = stock.optString("name");
					// double PERCENT = stock.optDouble("changepercent");

					if (SNAME.startsWith("*"))
					{
						continue;
					}

					String SYMBOL = stock.optString("symbol");
					SYMBOL = SYMBOL.substring(2);
					// if (SYMBOL.startsWith("002") || SYMBOL.startsWith("300"))
					{
						ids.add("" + SYMBOL);
					}
				}

				page++;
				if (page > pagecount)
				{
					break;
				}
			} catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
				break;
			}
		}

		return ids;
	}

	// 微博股票提及数热力图
	public List<WeiboRef> getWeiboHotInfo(String code)
	{
		// CNHOUR12
		// CNHOUR24
		// CNDAY7
		// CNDAY30

		String callback = "var%20AHM=";// "100032";
		Map<String, String> map = new HashMap<String, String>();
		map.put("code", code);
		map.put("callback", callback);

		// http://data.finance.sina.com.cn/api/openapi.php/WeiboReferService.getListSymbol

		try
		{
			List<NameValuePair> para = Utils.getParam(map);
			URI uri = new URIBuilder().setScheme("http").setHost("data.finance.sina.com.cn").setPath("/api/openapi.php/WeiboReferService.getListSymbol").setParameters(para).build();
			HttpGet httpmethod = new HttpGet(uri);

			httpmethod.addHeader("Accept", "*/*");
			httpmethod.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			httpmethod.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
			httpmethod.addHeader("Connection", "keep-alive");

			httpmethod.addHeader("DNT", "1");
			httpmethod.addHeader("Host", "data.finance.sina.com.cn");
			httpmethod.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");
			for (int i = 0; i < 3; i++)
			{
				try
				{
					HttpRequestFutureTask<String> futur_ret = requestExecService.execute(httpmethod, HttpClientContext.create(), new StringResponseHandler());
					String ret = futur_ret.get();
					if (ret != null)
					{
						// System.out.println(ret);
						String body = ret.substring(ret.indexOf("=(") + 2, ret.lastIndexOf(")"));
						// System.out.println(body);
						return getWeiboResult(body);
					}
				} catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private JSONObject print(String str)
	{
		JSONObject jsonObject = new JSONObject(str);
		for (String key : jsonObject.keySet())
		{
			System.out.println(key + ":" + jsonObject.opt(key));
		}

		return jsonObject;

	}

	private JSONArray printHqinfo(String str)
	{
		JSONArray jsonObject = new JSONArray(str);
		for (int i = 0; i < jsonObject.length(); i++)
		{
			System.out.println("--------------------------------");

			JSONObject data = (JSONObject) jsonObject.get(i);
			for (String key : data.keySet())
			{
				System.out.println(key + ":" + data.opt(key));
			}
			String sg_id = data.optString("sg_id");
			String newvalue = data.optString("newvalue");
			String dealvalue = data.optString("dealvalue");
			String newcost = data.optString("newcost");
		}

		return jsonObject;

	}

	private JSONObject printStockHold(String str)
	{
		JSONObject jsonObject = new JSONObject(str);
		// for (String key : jsonObject.keySet())
		// {
		// System.out.println(key + ":" + jsonObject.opt(key));
		// }

		String stockhold = jsonObject.optString("stockhold");
		System.out.println(stockhold + ":" + stockhold);

		JSONArray datas = (JSONArray) jsonObject.opt("data");
		for (int i = 0; i < datas.length(); i++)
		{
			JSONObject data = (JSONObject) datas.get(i);
			// System.out.println("[" + i + "]=" + data);

			// for (String key : data.keySet())
			// {
			// System.out.println(key + ":" + data.opt(key));
			// }

			System.out.println("--------------------------------");

			System.out.println("sg_id=" + data.optString("sg_id"));
			System.out.println("StartDate=" + data.optString("StartDate"));
			System.out.println("StockCode=" + data.optString("StockCode"));
			System.out.println("CurrentValue=" + data.optString("CurrentValue"));

			// sg_id:69974
			// StartDate:2015-09-30 09:39:29
			// StockCode:3*****
			// CurrentValue:6852240.000

			// StockFund:6871817.330
			// stockhold:69974

			// contest_id:10000
			// EndDate:0000-00-00 00:00:00
			// sid:1778730363
			// TodaySell:0

			// CostFund:6812996.070
			// T2AvailSell:0
			// zy_price:null
			// HoldPercent:99.720
			// zs_price:null
			// T3AvailSell:0

		}

		return jsonObject;

	}

	private JSONObject printHistoryTradeInfo(String str)
	{
		JSONObject jsonObject = new JSONObject(str);
		for (String key : jsonObject.keySet())
		{
			System.out.println(key + ":" + jsonObject.opt(key));
		}

		String stockhold = jsonObject.optString("stockhold");
		System.out.println(stockhold + ":" + stockhold);

		JSONArray datas = (JSONArray) jsonObject.opt("data");
		for (int i = 0; i < datas.length(); i++)
		{
			System.out.println("--------------------------------");
			JSONObject data = (JSONObject) datas.get(i);
			// System.out.println("[" + i + "]=" + data);

			// for (String key : data.keySet())
			// {
			// System.out.println(key + ":" + data.opt(key));
			// }
			String sg_id = data.optString("sg_id");
			String StockName = data.optString("StockName");
			String StockCode = data.optString("StockCode");
			String DealTime = data.optString("DealTime");

			String statement_name = data.optString("statement_name");
			String statement_type = data.optString("statement_type");
			String type = data.optString("type");

			String DealPrice = data.optString("DealPrice");
			String DealAmount = data.optString("DealAmount");

			System.out.println("sg_id=" + sg_id);
			System.out.println("StockName=" + StockName);
			System.out.println("StockCode=" + StockCode);
			System.out.println("DealTime=" + DealTime);
			System.out.println("statement_name=" + statement_name);
			System.out.println("statement_type=" + statement_type);
			System.out.println("type=" + type);
			System.out.println("DealPrice=" + DealPrice);
			System.out.println("DealAmount=" + DealAmount);

			// statement_name:卖出,statement_type:3
			// statement_name:买入,statement_type:2

		}

		return jsonObject;

	}

	private JSONObject getQueryResult(String str)
	{
		JSONObject jsonObject = new JSONObject(str);
		for (String key : jsonObject.keySet())
		{
			System.out.println(key + ":" + jsonObject.opt(key));
		}

		String day = jsonObject.optString("day");
		String count = jsonObject.optString("count");
		String code = jsonObject.optString("code");

		String fields = jsonObject.optString("fields");
		System.out.println(fields + ":" + fields);

		JSONArray items = (JSONArray) jsonObject.opt("items");
		for (int i = 0; i < items.length(); i++)
		{
			System.out.println("--------------------------------");
			JSONArray data = (JSONArray) items.get(i);
			System.out.println("[" + i + "]=" + data);

			// for (int j = 0; j < data.length();j++)
			// {
			// System.out.println("[" + j + "]=" + data.get(j));
			// }

			// String sg_id = data.optString("sg_id");
			// String StockName = data.optString("StockName");
			// String StockCode = data.optString("StockCode");
			// String DealTime = data.optString("DealTime");
			//
			// String statement_name = data.optString("statement_name");
			// String statement_type = data.optString("statement_type");
			// String type = data.optString("type");
			//
			// String DealPrice = data.optString("DealPrice");
			// String DealAmount = data.optString("DealAmount");
			//
			// System.out.println("sg_id=" + sg_id);
			// System.out.println("StockName=" + StockName);
			// System.out.println("StockCode=" + StockCode);
			// System.out.println("DealTime=" + DealTime);
			// System.out.println("statement_name=" + statement_name);
			// System.out.println("statement_type=" + statement_type);
			// System.out.println("type=" + type);
			// System.out.println("DealPrice=" + DealPrice);
			// System.out.println("DealAmount=" + DealAmount);

		}

		return jsonObject;

	}

	

	private JSONArray getMoneyFlowResult(String str)
	{
		JSONArray items = new JSONArray(str);
		for (int i = 0; i < items.length(); i++)
		{
			// System.out.println("--------------------------------");
			JSONObject data = (JSONObject) items.get(i);
			// System.out.println("[" + i + "]=" + data);
			// for (String key : data.keySet())
			// {
			// System.out.println(key + ":" + data.opt(key));
			// }

			String name = data.optString("name");
			String category = data.optString("category");
			String netamount = data.optString("netamount");
			String ratioamount = data.optString("ratioamount");

			String avg_changeratio = data.optString("avg_changeratio");
			String ts_symbol = data.optString("ts_symbol");
			String ts_name = data.optString("ts_name");

			String ts_changeratio = data.optString("ts_changeratio");
			String ts_ratioamount = data.optString("ts_ratioamount");

			// System.out.println("name=" + name);
			// System.out.println("category=" + category);
			// System.out.println("netamount=" + netamount);
			// System.out.println("ratioamount=" + ratioamount);
			// System.out.println("avg_changeratio=" + avg_changeratio);
			// System.out.println("ts_symbol=" + ts_symbol);
			// System.out.println("ts_name=" + ts_name);
			//
			// System.out.println("ts_changeratio=" + ts_changeratio);
			// System.out.println("ts_ratioamount=" + ts_ratioamount);

		}
		return items;
	}

	private JSONObject getStockMoneyFlowResult(String str)
	{
		JSONObject data = new JSONObject(str);
		for (String key : data.keySet())
		{
			System.out.println("[" + key + "]=" + data.opt(key));
		}

		String r0_in = data.optString("r0_in");
		String r0_out = data.optString("r0_out");
		String r0 = data.optString("r0");

		System.out.println("r0_in=" + r0_in);
		System.out.println("r0_out=" + r0_out);
		System.out.println("r0=" + r0);// 净流入

		System.out.println("主力净流入、特大单净流入=" + (Double.valueOf(r0_in) - Double.valueOf(r0_out)) / 10000);

		String r1_in = data.optString("r1_in");
		String r1_out = data.optString("r1_out");
		String r1 = data.optString("r1");

		System.out.println("r1_in=" + r1_in);
		System.out.println("r1_out=" + r1_out);
		System.out.println("r1=" + r1);// 净流入

		System.out.println("大单净流入=" + (Double.valueOf(r1_in) - Double.valueOf(r1_out)) / 10000);

		String r2_in = data.optString("r2_in");
		String r2_out = data.optString("r2_out");
		String r2 = data.optString("r2");

		System.out.println("r2_in=" + r2_in);
		System.out.println("r2_out=" + r2_out);
		System.out.println("r2=" + r2);// 净流入

		System.out.println("小单净流入=" + (Double.valueOf(r2_in) - Double.valueOf(r2_out)) / 10000);

		String r3_in = data.optString("r3_in");
		String r3_out = data.optString("r3_out");
		String r3 = data.optString("r3");

		System.out.println("r3_in=" + r3_in);
		System.out.println("r3_out=" + r3_out);
		System.out.println("r3=" + r3);// 净流入

		System.out.println("散户净流入、散单净流入=" + (Double.valueOf(r3_in) - Double.valueOf(r3_out)) / 10000);

		String r0x_ratio = data.optString("r0x_ratio");
		System.out.println("主力罗盘度=" + r0x_ratio); // 净流入百分比

		String trade = data.optString("trade");
		String changeratio = data.optString("changeratio");
		String turnover = data.optString("turnover");
		String netamount = data.optString("netamount");
		String volume = data.optString("volume");// 成交量股数
		String curr_capital = data.optString("curr_capital");

		System.out.println("trade=" + trade);// 当前价格
		System.out.println("changeratio=" + changeratio);// 当前涨幅
		System.out.println("turnover=" + turnover);// 需要除100，得百分比
		System.out.println("netamount=" + netamount);// 净流入
		System.out.println("volume=" + volume);// 净流入
		System.out.println("curr_capital=" + curr_capital);// 净流入

		System.out.println("主力净流入、特大单净流入=" + (Double.valueOf(r0_in) - Double.valueOf(r0_out)) / (Double.valueOf(trade) * Double.valueOf(volume)));

		return data;
	}

	private JSONArray getBankuaiMoneyFlowStockResult(String str)
	{
		JSONArray items = new JSONArray(str);
		for (int i = 0; i < items.length(); i++)
		{
			// System.out.println("--------------------------------");
			JSONObject data = (JSONObject) items.get(i);
			// System.out.println("[" + i + "]=" + data);
			// for (String key : data.keySet())
			// {
			// System.out.println(key + ":" + data.opt(key));
			// }

			// String name = data.optString("name");
			// String symbol = data.optString("symbol");
			// String netamount = data.optString("netamount");
			// String ratioamount = data.optString("ratioamount");
			// String trade = data.optString("trade");
			// String changeratio = data.optString("changeratio");
			// String turnover = data.optString("turnover");
			//
			// System.out.println("name=" + name);
			// System.out.println("symbol=" + symbol);
			// System.out.println("trade=" + trade);// 当前价格
			// System.out.println("changeratio=" + changeratio);// 当前涨幅
			//
			// System.out.println("netamount=" + netamount);// 净流入
			// System.out.println("ratioamount=" + ratioamount); // 净流入百分比
			// System.out.println("turnover=" + turnover);// 需要除100，得百分比

		}
		return items;
	}

	private SinaParameter getPreLoginPara(String str)
	{
		JSONObject jsonObject;
		try
		{
			SinaParameter para = new SinaParameter();
			jsonObject = new JSONObject(str);
			para.rsakv = jsonObject.optString("rsakv");
			para.servertime = jsonObject.optString("servertime");
			para.pcid = jsonObject.optString("pcid");
			para.nonce = jsonObject.optString("nonce");
			para.pubkey = jsonObject.optString("pubkey");

			return para;
		} catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// for (String key : jsonObject.keySet())
		// {
		// System.out.println(key + ":" + jsonObject.opt(key));
		// }

		return null;

	}

	public static void main(String[] args)
	{
		DefaultSinaDataUtilis netdata = new DefaultSinaDataUtilis();
		// netdata.login();
		// netdata.loginWithVeryCode();

//		 Level l = netdata.getRealLevelInfo("002594");
//		 l.print();
//		 SimpleRealInfo sinfo = netdata.getSimpleRealLevelInfo("002594");
//		 sinfo.print();

//		 List<Level2_ZJLXNetInfo> list =
//		 netdata.getLevel2Stock5dayMinuteZJLXInfos("002594");
//		 {
//		 for (Level2_ZJLXNetInfo info : list)
//		 {
//		 info.print();
//		 }
//		 }

		// netdata.getLevel2DapanZJLXInfos();

		// netdata.getLevel2DapanHistoryZJLXInfos();

		// List<Level2_ZJLXNetInfo> list =
		// netdata.getLevel2Dapan5dayMinuteZJLXInfos();
		// {
		// for (Level2_ZJLXNetInfo info : list)
		// {
		// info.print();
		// }
		// }
//		List<Level2_HangyeZJLXNetInfo> list = netdata.getLevel2HangyeZJLXInfos();
//		{
//			for (Level2_HangyeZJLXNetInfo info : list)
//			{
//				info.print();
//			}
//		}

		// long t = System.currentTimeMillis();
		// String type = "";// "cyb";// type:zxqy,cyb,
		// List<Level2_ZJLXNetInfo> list = netdata.getLevel2ZJLXMartInfos(type);
		// for (Level2_ZJLXNetInfo info : list)
		// {
		// info.print();
		// }
		// long delta = (System.currentTimeMillis() - t) / 1000;
		// System.out.println(delta + ":" + list.size());

		// int page = 1;
		// int num = 1000;
		// int asc = 0;
		// double min_percent = 0.095;
		//
		// List<Level2RankInfo> list = netdata.getChangeRankingList(num,
		// min_percent);
		// for (Level2RankInfo stock : list)
		// {
		// if (Utils.isLimitup(stock.low, stock.lastclose))
		// {
		// stock.print();
		// }
		// }

		// netdata.getChangeRankingList(page, num, asc);

		// netdata.getNewStockCheckData(null);

		// long max_MCAP = 300 * 10000 * 10000L;
		// double min_MFSUM = -10000;
		// int count = 200;
		// double min_percent = 0.07;
		// netdata.getConditionStocks(count, max_MCAP, min_percent);

		// netdata.getSubscribeInfo();

		// String mkt = "sz";
		// netdata.getMarketWeiboHotInfo(mkt);

		// String [] codes=new
		// String[]{"CNHOUR2","CNHOUR6","CNHOUR12","CNHOUR24"};
		// Map<String,WeiboRef> wrs=new HashMap<>();
		// for(String code:codes)
		// {
		// List<WeiboRef> list=netdata.getWeiboHotInfo(code);
		// if(list!=null)
		// {
		// for(WeiboRef wr:list)
		// {
		// wrs.put(wr.symbol, wr);
		// }
		// }
		// }
		// List<String> all=new ArrayList<>();
		// all.addAll(wrs.keySet());
		// int i=0;
		// for(WeiboRef wr:wrs.values())
		// {
		// System.out.println((i++)+":"+wr.symbol+"\t"+wr.name+"\t"+wr.REF);
		// }

		// String list =
		// "sh000001_zdp,sz399001_zdp,sz399300_zdp,sz399005_zdp,sz399102_zdp";
		// List<String> indexsymbols = new ArrayList<>();
		// indexsymbols.add("000001");
		// indexsymbols.add("399001");
		// indexsymbols.add("399300");
		// indexsymbols.add("399005");
		// indexsymbols.add("399102");
		//
		// netdata.getIndexInfo(indexsymbols);

		// String sid ="5276780493";// "1778730363";// 2880259462";
		// String cid = "100032";//"10000";// "100032";
		// int count = 10;
		//
		// JSONObject ret = netdata.getShockHoldInfo(sid, cid, count);
		// if (ret != null)
		// {
		// String stockhold = ret.optString("stockhold");
		// if (stockhold != null && !stockhold.equals(""))
		// {
		// String ids = stockhold;// "42766,42486,89";// "100032";
		// netdata.getHqInfo(sid, ids);
		// }
		// }
		//
		// int from = 0;
		// String sdate = "2015-09-01";
		// String edate = "";
		//
		// // sdate:2015-09-03
		// // edate:2015-10-03
		//
		// count = 20;
		// netdata.getHistoryTradeInfo(sid, cid, sdate, edate, from, count);

		// 查询符合条件的股票
		// int page=1;//start from 1;
		// int count=40;
		// String type="zxqy";//cyb：创业板,zxqy:中小板，hs_a：全部A股，dpzs：大盘指数
		// int order=0;//0:降序，1升序
		// String sort="changepercent";//trade:当前价格,changepercent:涨跌幅度
		//
		// netdata.getQueryInfo( page, count, type, sort, order);

		// int page = 1;// start from 1;
		// int num = 20;
		// int asc = 0;// 0:降序，1升序
		// String sort = "ratioamount";//
		// netamount：按净流入资金数量排序，ratioamount：净流入率排序，avg_changeratio：按涨幅排序
		// System.out.println("概念资金流向：");
		// // netdata.getMoneyFlowInfo_Concept(page, num, asc, sort);
		//
		// // 可以将概念和板块结合在一起确定当前资金的流向
		// System.out.println("板块资金流向：");
		// JSONArray ret = netdata.getMoneyFlowInfo_Bankuai(page, num, asc,
		// sort);
		// netdata.computeMoneyFlowExtreme(ret, sort, 2);
		// for (int i = 0; i < ret.length(); i++)
		// {
		// JSONObject data = (JSONObject) ret.get(i);
		// Boolean remarkable = data.getBoolean("显著");
		// if (remarkable)
		// {
		// String category = data.optString("category");
		// String bankuai = "0/" + category;// ,为空时，所有板块，"0/new_fjzz";//
		// // fenlei=0：按新浪板块定义分类，fenlei:2：按证监会定义板块分类，fenlei:1按概念板块分类
		// sort = "ratioamount";//
		// symbol：按代码排序，changeratio，按涨幅排序，turnover，按换手率，netamount：按净流入排序，ratioamount：净流入率排序，r0_ratio：主力净流入率排序
		// String shichang = "";// 市场，sh，sz
		// JSONArray stocks = netdata.getBankuaiMoneyFlowStocks(page, num, asc,
		// bankuai, shichang, sort);
		// netdata.computeMoneyFlowExtreme(stocks, sort, 1.5);
		// }
		// }

		// int page = 1;// start from 1;
		// int num = 5;
		// int asc = 0;// 0:降序，1升序
		// String bankuai = "0";// ,为空时，所有板块，"0/new_fjzz";//
		// // fenlei=0：按新浪板块定义分类，fenlei:2：按证监会定义板块分类，fenlei:1按概念板块分类
		// String sort = "ratioamount";//
		// symbol：按代码排序，changeratio，按涨幅排序，turnover，按换手率，netamount：按净流入排序，ratioamount：净流入率排序，r0_ratio：主力净流入率排序
		// String shichang = "";// 市场，sh，sz
		//
		// netdata.getBankuaiMoneyFlowStockInfo(page, num, asc, bankuai,
		// shichang, sort);

		// String daima = "sh600650";
		// netdata.getStockMoneyFlowInfo(daima);

		// level2 数据

		// List<String> indexsymbols = new ArrayList<>();
		// indexsymbols.add("000001");// 上证指数
		// indexsymbols.add("000300");// 沪深300
		//
		// indexsymbols.add("399001");// 深证成指
		// indexsymbols.add("399005");// 中小板指
		// indexsymbols.add("399006");// 创业板指
		//
		// List<String> symbols = new ArrayList<>();
		// // symbols.add("600797");
		// // symbols.add("002342");
		// symbols.add("600888");
		//
		// // netdata._getLevel2AuthenCodeInfo(symbols);
		// // netdata.getLevel2DetailInfo(symbols);
		//
		// SinaLevelFectcher fetcher = new SinaLevelFectcher(netdata, symbols,
		// indexsymbols,null,null);
		// Thread t = new Thread(fetcher);
		// t.start();
		//
		// List<String> addsymbols = new ArrayList<>();
		// addsymbols.add("002211");
		// addsymbols.add("002342");
		// addsymbols.add("600744");

		// netdata.getLeveL2ZJLXInfos(addsymbols);
		// netdata.getLevel1ZJLXInfos(addsymbols);

		// netdata.getSimpleRealLevelInfo(addsymbols);

		// for (int i = 0; i < addsymbols.size(); i++)
		// {
		// try
		// {
		// Thread.sleep(30000);
		// symbols.add(addsymbols.get(i));
		// fetcher.updateList(symbols);
		// } catch (InterruptedException e)
		// {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// }

		// List<String> _symbols = new ArrayList<>();
		// _symbols.add("002268");
		//
		//
		// Thread _t=new Thread(new SinaLevelFectcher(netdata,_symbols));
		// _t.start();
		//
		//
		// try
		// {
		// Thread.sleep(30000);
		// } catch (InterruptedException e)
		// {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// t.interrupt();

		 //netdata.getLevel2AuthenCodeInfo("002268");
		 //netdata.getLevel2DetailInfo("002268");

		// for (;;)
		// {
		//
		// try
		// {
		// netdata.getLevel2ZJLXInfo("002342");
		//
		// // netdata.getRealLevelInfo(symbols);
		// Thread.sleep(300);
		// } catch (InterruptedException e)
		// {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// }

		// String date="2012-09-10";
		// String symbol="002268";
		//
		// netdata.downloadCJMX( date, symbol);

		// String symbol = "002362";
		// netdata.getStockFenshiInfo(symbol);

		// String stime = "09:00:00";
		// String etime = "09:30:00";
		//
		// long l = System.currentTimeMillis();
		// netdata.getTodayZBInfo("002342", stime, etime);
		//
		// System.out.println((System.currentTimeMillis() - l) / 1000);

		// netdata.getLevel2FenshiCJMXInfo("002342");

		// netdata.getLevel2ZJLXInfo("002342");
		// netdata.getRealLevel2Info(symbols);

		// List<String> _symbols = new ArrayList<>();
		// _symbols.add("002268");
		// netdata.getRealLevel2Info(_symbols);

	}
}
